<?php

namespace App\Blocks;


use App\Models\GoodComment;
use App\Models\GoodCommentImage;
use App\Models\OrderScLog;
use App\Models\UserAddress;
use App\Models\UserMoneyLog;
use DB;
use App\Models\Orders;
use App\Models\Users;
use App\Models\Goods;
use App\Models\Brand;
use App\Models\Crowd;
use App\Models\OrderAddress;
use App\Models\OrderInfos;

class OrderBlock
{

    //我的订单列表
    public function my_orders($id, $status)
    {
        $order = new Orders();
        $orderInfo = new OrderInfos();
        $user = new Users();
        $orderadd = new OrderAddress();
        $crowd = new Crowd();
        $sql = DB::table($order->getTable() . ' as a')
            //买家名称(user)，商品名称(goods)，买家地址(address)，订单号，日期(orders)商品数量，商品价格，运费，订单总价格和商品属性
            ->select(
                'a.id',        //订单ID
                'a.crowd_id',  //群ID
                'e.name as c_name',       //群名
                'a.freight',    //运费
                'a.pay_total',  //总共需支付的总价
                'a.order_num',  //订单号
                'a.service_charge', //服务费
                'a.status',   //订单状态
                'c.nick_name',  //购买人
                'c.jg_im_username',
                'b.b_name',     //购买商品品牌名称
                'b.g_id as goods_id',     //商品id
                'b.name',       //购买商品名称
                'b.small_image', //商品列表图
                'b.buy_num',    //购买数量
                'b.now_price',  //购买商品现价
                'd.province',   //购买人所在省
                'd.name as add_name',
                'd.mobile',
                'd.city',       //购买人所在市、区
                'd.district',   //购买人所在县
                'd.address',    //详细地址
                'a.created_at'  //订单创建时间

            )
            ->leftJoin($orderInfo->getTable() . ' as b', 'a.id', '=', 'b.o_id')
            ->leftJoin($user->getTable() . ' as c', 'a.u_id', '=', 'c.id')
            ->leftJoin($orderadd->getTable() . ' as d', 'a.id', '=', 'd.o_id')
            ->leftJoin($crowd->getTable().' as e','a.crowd_id','=','e.id')
            ->where('a.u_id', $id)
            ->orderBy('created_at','desc');

        if (isset($status)) {
            $sql = $sql->where('status', $status);
        }
        $res = $sql->get();
        $message = ['未付款', '已支付', '已发货', '已收货', '已评价', '退款中', '已退款', '已取消'];

        foreach ($res as $re) {
            $re->message = $message[(int)$re->status];
        }
        return $res;
    }

    //我的订单详情
    public function my_orders_details($id)
    {
        $order = new Orders();
        $orderInfo = new OrderInfos();
        $user = new Users();
        $orderadd = new OrderAddress();
        $crowd = new Crowd();
        $sql = DB::table($order->getTable() . ' as a')
            //买家名称(user)，商品名称(goods)，买家地址(address)，订单号，日期(orders)商品数量，商品价格，运费，订单总价格和商品属性
            ->select(
                'a.id',        //订单ID
                'a.crowd_id',  //群ID
                'e.name as c_name',       //群名
                'a.freight',    //运费
                'a.pay_total',  //总共需支付的总价
                'a.order_num',  //订单号
                'a.service_charge', //服务费
                'a.status',   //订单状态
                'c.nick_name',  //购买人
                'c.jg_im_username',
                'b.b_name',     //购买商品品牌名称
                'b.g_id as goods_id',     //商品id
                'b.name',       //购买商品名称
                'b.small_image', //商品列表图
                'b.buy_num',    //购买数量
                'b.now_price',  //购买商品现价
                'd.province',   //购买人所在省
                'd.city',       //购买人所在市、区
                'd.district',   //购买人所在县
                'd.address',    //详细地址
                'd.name as add_name',
                'd.mobile',
                'a.created_at'  //订单创建时间

            )
            ->leftJoin($orderInfo->getTable() . ' as b', 'a.id', '=', 'b.o_id')
            ->leftJoin($user->getTable() . ' as c', 'a.u_id', '=', 'c.id')
            ->leftJoin($orderadd->getTable() . ' as d', 'a.id', '=', 'd.o_id')
            ->leftJoin($crowd->getTable().' as e','a.crowd_id','=','e.id')
            ->where('b.id', $id)
            ->orderBy('created_at','desc');

        if (isset($status)) {
            $sql = $sql->where('status', $status);
        }
        $res = $sql->first();
        $message = ['未付款', '已支付', '已发货', '已收货', '已评价', '退款中', '已退款', '已取消'];

        $res->message = $message[(int)$res->status];
        return $res;
    }

    //创建订单
    public function create_order($data)
    {
        $orders = new Orders();
        $log = new OrderScLog();
        $order_address = new OrderAddress();
        $infos = new OrderInfos();
        $order['u_id'] = $data['u_id'];
        $order['crowd_id'] = $data['crowd_id'];
        $order['service_charge'] = $data['service_charge'];
        $order['freight'] = $data['freight'];
        $order['g_total_price'] = $data['g_total_price'];
        $order['pay_total'] = $data['pay_total'];
        $order['created_at'] = date('Y-m-d H:i:s', time());
        $order['order_num'] = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        try {
            DB::beginTransaction();
            $orders_id = DB::table($orders->getTable())->insertGetId($order);

            $info_data = $this->created_order_info($data['g_id'], $orders_id);
            $info_data[0]['buy_num'] = $data['buy_num'];
            $add_data = $this->created_order_address($data['a_id'], $orders_id);
            $log_res = DB::table($log->getTable())->insert(array('o_id' => $orders_id, 'status' => 0));

            $add_res = DB::table($order_address->getTable())->insert($add_data);

            $info_res = DB::table($infos->getTable())->insert($info_data);
            if (!$orders_id || !$log_res || !$info_res || !$add_res) {
                DB::rollBack();
                return false;
            }

            DB::commit();
            return $orders_id;
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::debug($exception);
            return false;
        }


    }

    private function created_order_info($gid, $oid)
    {
        $good = new Goods();
        $Brand = new Brand();
        $good_res = DB::table($good->getTable() . ' as a')
            ->select('a.c_id', 'a.b_id', 'a.id as g_id', 'a.show_title', 'a.name', 'a.small_image', 'a.producing_area', 'a.unit', 'a.now_price', 'b.name as b_name')
            ->leftJoin($Brand->getTable() . ' as b', 'a.b_id', '=', 'b.id')
            ->where('a.id', $gid)->get();
        $good_data = json_decode(json_encode($good_res), true);
        $good_data[0]['o_id'] = $oid;
        $info_data[0]['created_at'] = date('Y-m-d H:i:s', time());
        return $good_data;
    }

    private function created_order_address($aid, $oid)
    {
        $Address = new UserAddress();
        $address_res = DB::table($Address->getTable())
            ->select('name', 'mobile', 'province', 'city', 'district', 'address')
            ->where('id', $aid)->get();
        $address_data = json_decode(json_encode($address_res), true);
        $address_data[0]['o_id'] = $oid;
        $address_data[0]['a_id'] = $aid;
        return $address_data;

    }

    public function CancelOrder($uid,$status,$order_id){
        $OrderModel = new Orders();
        if ($status==0){
            $is_status = 7;
            $message = "已取消";
        }else{
            $is_status = 5;
            $message = "退款中";
        }
        $res = DB::table($OrderModel->getTable())
            ->where('u_id',$uid)
            ->where('id',$order_id)
            ->update(['status'=>$is_status]);

        if ($res){

            return ['status' => $is_status,'message'=>$message];
        }else{
            return false;
        }
    }

    public function TakeOrder($uid,$order_id){
//        $OrderModel = new Orders();
//        $order = DB::table($OrderModel->getTable())
//            ->where('id', $order_id)
//            ->first();
//        if (!$order){
//            return ['status' => 3,'message'=>$message];
//        }
//        $message = "已收货";
        try {
            if (!isset($uid)) {
                return ['参数错误'];
            }
            $OrderModel = new Orders();
            $user = new Users();
            $userMoney = new UserMoneyLog();
            $crowd = new Crowd();
            $orderInfoModel = new OrderInfos();
//            验存

            $order = DB::table($OrderModel->getTable())
                ->where('id', $order_id)
                ->first();
            if (!$order){
                return ['订单不存在'];
            }
            if ($order->status==3){
                return ['订单已收货'];
            }
            $crowd = DB::table($crowd->getTable())
                ->where('id', $order->crowd_id)
                ->first();

            if (!$crowd){
                return ['订单信息有误'];
            }
            $crowdUser = DB::table($user->getTable())
                ->where('id', $crowd->uid)
                ->first();
            if (!$crowdUser){
                return ['订单信息有误'];
            }
            DB::beginTransaction();
            try {

                $res = DB::table($OrderModel->getTable())
                    ->where('u_id',$uid)
                    ->where('id',$order_id)
                    ->update(['status'=>3]);
                if (!$res){
                    return ['操作失败'];
                }
                $userMoneyUsave = DB::table($user->getTable())->where('id', $crowdUser->id)->increment('balance',$order->pay_total);
                if (!$userMoneyUsave){
                    return ['操作失败'];
                }
                $remake = DB::table($orderInfoModel->getTable())->where('o_id',$order_id)->value('name');
                $data = [
                    'u_id'=>$crowdUser->id,
                    'type'=>0,
                    'order_id'=>$order_id,
                    'money'=>$order->pay_total,
                    'remake'=> $remake,
                    'created_at'=>date('Y-m-d H:i:s', time())
                ];
                $userMoneyLog = DB::table($userMoney->getTable())->insertGetId(
                    $data
                );
                if (!$userMoneyLog){
                    return ['操作失败'];
                }

                DB::commit();
                return $res;
            } catch (\Exception $error) {
                DB::rollBack();
                \Log::debug($error);
                dd($error);
            }
        } catch (\Exception $exception) {
            \Log::error($exception);
            dd($exception);
        }

    }

    public function saveGoodComment($uid,$data){
        try {
            if (!isset($uid)) {
                return ['参数错误'];
            }
//            是否已经评价
            $OrderModel = new Orders();
            $goodComment = new GoodComment();
            $order = DB::table($OrderModel->getTable())
                ->where('id', $data['order_id'])
                ->first();
            if (!$order){
                return ['订单不存在'];
            }
            if ($order->u_id!=$uid){
                return ['订单信息有误'];
            }
            $order = DB::table($goodComment->getTable())
                ->where('order_id', $data['order_id'])
                ->where('u_id', $uid)
                ->first();
            if ($order){
                return ['订单已评价'];
            }

            $goodComment = new GoodComment();
            $goodCommentImage = new GoodCommentImage();
            DB::beginTransaction();
            try {
                $goodCommentData = [
                    'order_id' => $data['order_id'],
                    'u_id' => $uid,
                    'content' => $data['content'],
                    'goods_id' => $data['goods_id'],
                    'goods_name' => $data['goods_name'],
                    'star' => $data['star']
                ];

                $goodCommentId = DB::table($goodComment->getTable())->insertGetId($goodCommentData);

                if (isset($data['image'])){
                    foreach ($data['image'] as $v) {
                        $img_data = ['img_url' => $v, 'comment_id' => $goodCommentId];
                        DB::table($goodCommentImage->getTable())->insertGetId($img_data);
                    }

                }

                DB::table($OrderModel->getTable())->where('id', $data['order_id'])
                    ->update(['status' => 4]);
                DB::commit();

                return $goodCommentId;
            } catch (\Exception $error) {
                DB::rollBack();
                \Log::debug($error);
            }
        } catch (\Exception $exception) {
            \Log::error($exception);
        }
    }


    private function __goodsSql($search){
        $goodComment             = new GoodComment();
        $goodCommentImage        = new GoodCommentImage();
        $user                    = new Users();
        $goods                   = new Goods();
        $order                   = new Orders();
        $sql = DB::table($goodComment->getTable() . ' as gc')
            ->select(
                'gc.id',
                'gc.content',
                'gc.goods_name',
                'gc.star',
                'o.order_num',
                'u.nick_name',
                'u.headimgurl',
                'gc.create_time'
//                DB::raw("date_format('create_time', '%Y-%m-%d') as time")
            )
            ->leftJoin($user->getTable() . ' as u', 'gc.u_id', '=', 'u.id')
            ->leftJoin($goods->getTable() . ' as g', 'gc.goods_id', '=', 'g.id')
            ->leftJoin($order->getTable() . ' as o', 'gc.order_id', '=', 'o.id');


        if(isset($search['goods_id'])){
            $sql->where('gc.goods_id', $search['goods_id']);
        }
        return $sql;
    }

    /**
     * 获取评论列表
     * @param $search
     * @param $page
     * @param $pageSize
     */
    public function commentList($search, $page, $pageSize){
        $sql = $this->__goodsSql($search);

        $goods = $sql->skip(($page - 1) * $pageSize)->take($pageSize)
            ->orderBy('gc.create_time', 'desc')
            ->get();
        $goods = json_decode(json_encode($goods),true);
        $goodCommentImage        = new GoodCommentImage();
        foreach ($goods as $k=>&$v){

            $v['img_url'] = DB::table($goodCommentImage->getTable())
                ->where('comment_id', $v['id'])
                ->get();
        }

        return $goods;
    }

    public function commentListPagination(array $search, int $page = 1, int $pageSize = 20){
        $sql = $this->__goodsSql($search);
        return [
            'total' => $sql->count(),
            'pageSize' => $pageSize,
            'current' => $page,
        ];
    }

}